<template>
  <div class="asset-info">
    <el-card>
      <!-- 功能菜单 -->
      <div>
        <el-row>
          <el-col :span="6">
            <span class="top-label">选择分类</span>
            <el-cascader
            :disabled="!enableFilter"
            clearable
            v-model="filter.cid"
            :options="categoryGroup"
            :props="{ expandTrigger: 'hover', label: 'name', value: 'id', emitPath: false }">
            </el-cascader>
          </el-col>
          <el-col :span="6">
            <span class="top-label">选择部门</span>
            <el-select v-model="filter.depaId" clearable placeholder="请选择" :disabled="!enableFilter">
              <el-option v-for="department in depaList" :key="department.id" :label="department.name" :value="department.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="按名称搜索" v-model="keyWord" clearable style="width: 60%;" :disabled="!enableFilter"></el-input>
            <el-button type="primary" icon="el-icon-search" @click="selectAsset" :disabled="!enableFilter">搜索</el-button>
          </el-col>
          <el-col :span="6">
            <div style="float: right; margin-right: 20px;">
              <el-button type="primary" icon="el-icon-circle-plus-outline" @click="insertAsset">新增记录</el-button>
              <!-- <el-button type="danger" icon="el-icon-delete" @click="deleteAssetList">批量删除</el-button> -->
            </div>
          </el-col>
        </el-row>
        <el-row>
          <div style="margin: 10px auto 0;">
            <el-button-group>
              <el-button size="mini" type="primary" @click="dataType = 1">全部</el-button>
              <el-button size="mini" type="primary" @click="dataType = 2">可预定</el-button>
              <el-button size="mini" type="primary" @click="dataType = 3">已预定</el-button>
            </el-button-group>
          </div>
        </el-row>
      </div>
      <!-- 数据表格 -->
      <div class="box-table">
        <el-table
          height="450"
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          :data="assetList" style="width: 100%;"
          highlight-current-row
          stripe>
          <!-- <el-table-column type="selection" width="50"></el-table-column> -->
          <el-table-column prop="id" label="id" width="60">
          </el-table-column>
          <el-table-column prop="cid" label="分类" width="120" show-overflow-tooltip :formatter="row => this.categoryMap.get(row.cid)">
          </el-table-column>
          <el-table-column label="所属部门" width="100">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>所属仓库: {{ depositoryMap.get(scope.row.depoId) }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ departmentMap.get(scope.row.depaId) }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="brandId" label="品牌" width="120" :formatter="row => brandMap.get(row.brandId)">
          </el-table-column>
          <el-table-column prop="name" label="名称" width="100" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="number" label="数量" width="60">
          </el-table-column>
          <el-table-column prop="price" label="单价/元" width="80" :formatter="r => $numeral(r.price).format('0,0.00')">
          </el-table-column>
          <el-table-column label="净残值/元" width="80" :formatter="r => $numeral(r.netSalvage).format('0,0.00')">
          </el-table-column>
          <el-table-column prop="deprRate" label="月折旧率" width="80" :formatter="r => $numeral(r.deprRate).format('(0.00%)')">
          </el-table-column>
          <el-table-column prop="status" label="资产状态" width="80" :formatter="row => statusMap.get(row.status)">
          </el-table-column>
          <el-table-column prop="putDate" label="入库日期" width="120">
          </el-table-column>
          <el-table-column label="领用人" min-width="80">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top" v-if="scope.row.userId">
                <p>到期时间: {{ scope.row.dueDate }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ userMap.get(scope.row.userId) }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="150">
            <template slot-scope="scope">
              <el-tooltip content="编辑" placement="top">
                <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="updateAsset(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="deleteAsset(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip content="置为闲置" placement="top"
                v-if="scope.row.restore">
                <el-button size="mini" type="primary" icon="el-icon-refresh" circle @click="resetToDefault(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip v-if="scope.row.reserve" content="预定" placement="top">
                <el-button @click="reserveAsset(scope.row.id)" size="mini" type="success" icon="el-icon-plus" circle></el-button>
              </el-tooltip>
              <el-tooltip v-else-if="scope.row.cancel" content="取消预定" placement="top">
                <el-button @click="cancelReserve(scope.row)" size="mini" type="primary" icon="el-icon-minus" circle></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="box-pagination">
        <el-pagination
          :disabled="!enableFilter"
          background
          @size-change="val => this.pagination.pageSize = val"
          @current-change="val => this.pagination.currentPage = val"
          :current-page="pagination.currentPage"
          :page-sizes="pagination.pageSizes" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>
    <asset-form
      :dialog-visible.sync="dialogVisible"
      :id='id'
      :depa-list="depaList"
      :depo-list="depoList"
      :brand-list="brandList"
      :category-list="categoryGroup"
      @success="selectAsset()">
    </asset-form>
  </div>
</template>

<script>
import assetForm from '@/components/pages/asset/AssetForm'

import * as common from '@/common'
import * as asset from '@/api/asset'
import * as user from '@/api/user'
import * as category from '@/api/category'
import * as brand from '@/api/brand'
import * as department from '@/api/department'
import * as depository from '@/api/depository'

import statusMap from '@/data/assetStatus'

export default {
  name: 'AssetInfo',
  data () {
    return {
      assetList: [], // 资产信息
      depaList: [], // 部门信息
      depoList: [],
      categoryList: [], // 分类信息
      brandList: [],
      filter: { // 过滤器
        cid: '',
        depaId: ''
      },
      userMap: new Map(),
      keyWord: '',
      pagination: { // 分页器
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20]
      },
      statusMap,
      loading: false,
      dialogVisible: false,
      id: 0,
      enableFilter: true,
      dataType: 1
    }
  },
  created () {
    // 1. 分页查询
    console.log(`[asset-info:create]:select-asset`)
    this.selectAsset()
    // 2. 获取部门信息
    department.selectAll().then(resp => {
      this.depaList = resp.data.data
    }).catch(error => console.error(`${error}`))
    // 3. 获取仓库信息
    depository.selectAll().then(resp => {
      this.depoList = resp.data.data
    }).catch(error => console.error(error))
    // 4. 获取品牌信息
    brand.selectAll().then(resp => {
      this.brandList = resp.data.data
    }).catch(error => console.error(`${error}`))
    // 5. 获取分类信息
    category.selectAll(this.$axios).then(resp => {
      this.categoryList = resp.data.data
    }).catch(error => console.log(error))
  },
  watch: {
    pagination: {
      handler: function () {
        console.log(`[asset-info:watch]:pagination:select-asset`)
        this.selectAsset()
      },
      deep: true
    },
    filter: {
      handler: function () {
        console.log(`[asset-info:watch]:filter:select-asset`)
        this.selectAsset()
      },
      deep: true
    },
    dataType: function (val) {
      let user = this.$store.state.user
      console.log(`[asset-info:watch] - dataType: ${val}`)
      if (val === 1) {
        this.selectAsset()
        this.enableFilter = true
      } else if (val === 2) {
        // 可预定
        this.loading = true
        this.enableFilter = false
        asset.selectReserve(user.depaId, 0).then(resp => {
          this.assetList = resp.data
          this.assetList.forEach(e => { e.reserve = true })
          this.loading = false
        }).catch(() => { this.loading = false })
      } else {
        // 已预定
        this.loading = true
        this.enableFilter = false
        asset.selectByUser(user.id).then(resp => {
          this.assetList = resp.data
          this.assetList.forEach(e => { e.cancel = true })
          this.loading = false
        }).catch(() => { this.loading = false })
      }
    }
  },
  computed: {
    categoryGroup: function () {
      let baseGroup = this.categoryList.filter(item => item.pid === 0)
      baseGroup.forEach(item => {
        item.children = this.categoryList.filter(e => e.pid === item.id)
      })
      return baseGroup
    },
    brandMap: function () {
      return common.toMap(this.brandList, 'id', 'name')
    },
    categoryMap: function () {
      const map = new Map()
      this.categoryGroup.forEach(item => {
        item.children.forEach(child => {
          map.set(child.id, item.name + ' / ' + child.name)
        })
      })
      return map
    },
    departmentMap: function () {
      return common.toMap(this.depaList, 'id', 'name')
    },
    depositoryMap: function () {
      return common.toMap(this.depoList, 'id', 'name')
    }
  },
  methods: {
    // 分页查询
    selectAsset () {
      this.loading = true
      asset.selectByPage({
        page: this.pagination.currentPage,
        rows: this.pagination.pageSize,
        cid: this.filter.cid,
        depaId: this.filter.depaId,
        keyWord: this.keyWord
      }).then(resp => {
        this.assetList = resp.data.data
        let user = this.$store.state.user
        // 数据处理
        this.assetList.forEach(item => {
          // 是否可预定
          item.reserve = item.status === 0 && user.depaId === item.depaId
          // 是否可取消
          item.cancel = item.status === 1 && user.id === item.userId
          // 是否可置为闲置
          item.restore = (item.status === 3 || item.status === 4) && user.depaId === item.depaId
        })
        this.getUserList()
        this.pagination.total = resp.data.total
        this.loading = false
      }).catch(() => {
        this.$notify.error({title: '提示', message: '数据加载失败'})
        this.loading = false
      })
    },
    // 获取用户信息列表
    getUserList () {
      let set = new Set()
      this.assetList.forEach(e => { set.add(e.userId) })
      if (set.size === 0) return
      user.selectByIds(set).then(resp => {
        this.userMap = common.toMap(resp.data, 'id', 'name')
      }).catch(_ => {
        this.$notify.error('关联用户信息获取失败')
      })
    },
    // 新增资产
    insertAsset () {
      this.dialogVisible = true
      this.id = 0
    },
    // 修改资产信息
    updateAsset (id) {
      this.id = id
      this.dialogVisible = true
    },
    // 资产预定
    reserveAsset (id) {
      console.log(`[asset-info:reserve:id]:${id}`)
      asset.changeStatus(id, { to: 1, day: 7 }).then(resp => {
        this.$notify.success({title: '提示', message: '资产预定成功'})
        this.selectAsset()
      }).catch(_ => {
        this.$notify.error({title: '提示', message: '资产预定失败'})
      })
    },
    // 取消预定
    cancelReserve (item) {
      if (this.$store.state.user.id !== item.userId) {
        this.$notify.error('取消预定失败')
        return
      }
      console.log(`[asset-info:cancel-reserve:id]: ${item.id}`)
      asset.changeStatus(item.id, {to: 0}).then(resp => {
        this.$notify.success('已取消预定')
        this.selectAsset()
      }).catch(error => {
        this.$notify.error('取消失败')
        console.log(error)
      })
    },
    // 资产状态重置为闲置
    resetToDefault (id) {
      asset.changeStatus(id, {to: 0}).then(resp => {
        this.$notify.success('资产状态已重置')
        this.selectAsset()
      }).catch(e => {
        let msg = e.response !== null ? e.response.data.message : '请求超时'
        this.$notify.error(msg)
      })
    },
    // 删除资产信息
    deleteAsset (id) {
      console.log(`[asset-info:delete:id]: ${id}`)
      common.deleteConfirm(this, false).then(() => {
        // 进行删除
        asset.remove(id).then(resp => {
          this.$notify.success({title: '提示', message: '资产信息已删除'})
          this.selectAsset()
        }).catch(error => {
          console.error(`[AssetInfo:deleteAsset] ${error}`)
        })
      }).catch(() => {
        this.$message('操作取消')
      })
    }
  },
  components: {
    assetForm
  }
}
</script>

<style scoped>
  .asset-info {
    margin: 10px 10px;
  }
  .top-label {
    display: inline-block;
    margin: auto 10px;
    font-weight: bold;
  }
  .box-table {
    margin: 10px 10px;
    border: 1px solid gainsboro;
    min-height: 450px;
  }
  .box-pagination {
    margin: 10px auto;
  }
</style>
